
const app = getApp()     //全局数据
// 导入请求
import {request} from "../../request/index2"
Page({
    // 定义data
    data:{
      
        // 题目数据
        examdata:null,
        // 题目长度
        examlength:null,
        // title表示当前的题目索引
        title: 0,
        radio: null,
        // 点击获得答案进行保存
        radioarr: [],
        // 题目的所有答案
        answer: [],
        // 记录分数
        grade: 0,
        // 监听滑动所需要的值
        startX: null,
        startY: null,
        // 倒计时
        time: 5400000,
        timeData: {},
        // 记录错题索引
        errorindex: {},
        //记录错题的id 
        errorID: [],
        // 记录对的题目
        correctindex: {},
        // 记录对的题的ID
        correctID: [],
        // 试卷类型
        shijuantype: "suiji",
        shijuandata:null,
        paperId:null,
        paperName:null,
        dui:null,
        cuo:null,
        // question_list:[],
        // question_num:0,
        collection:[],
        click: false,
        show: false,
        error_question: [],
        correct_question: [],
        },

        onLoad(options){
            // 获取试卷类型
            // console.log(options);
            let shijuantype = options.paperTable
            // console.log(shijuantype);
            this.setData({ shijuantype})
            // 初始化数据
            this.initdata();
            // 
            this.checkshijuan();


            
        },

        onUnload: function () {
            let shijuantype = this.data.shijuantype;
            if(shijuantype!="suiji"){
              this.subexam()
            }else{
              this.subsuiji();
            }


            let id = wx.getStorageSync('userID')
        // console.log(id);
        let question = {
            "correctid": this.data.correct_question,
            "errorid": this.data.error_question,
            "index": this.data.title,
            "tixing": this.data.tixing,
            "userid": id
          }

          // 增加刷题记录
            wx.request({
                url: app.globalData.baseUrl+'/record/shuati',
                method: 'POST',
                data: question,
                success(res) {
                console.log(res)
                }
            })

            // 增加题目收藏
            wx.request({
                url: app.globalData.baseUrl+'/record/collection',
                method: 'POST',
                data: {
                collectid: this.data.collection,
                userid: id
                },
                success(res) {
                console.log(res)
                }
            })
            
          },
// 收藏
          collection(e){
            // console.log(e);
            if(this.data.collection.indexOf(this.data.examdata[this.data.title].questionid) == -1){
                this.data.collection.push(this.data.examdata[this.data.title].questionid)
                this.data.examdata[this.data.title].collected = true;
                          let examdata = this.data.examdata
                          // console.log(question_list);
                          this.setData({
                              examdata
                          })
                          console.log("收藏成功");
            }
            else{
                // 取消题目收藏
               this.data.examdata[this.data.title].collected = false;
               let examdata = this.data.examdata;
               this.setData({
                examdata
               })
               let index = this.data.collection.indexOf(this.data.examdata[this.data.title].questionid)
               // console.log(index);
               let collection = this.data.collection
               // console.log(collection);
               collection.splice(index,1)
               // console.log(collection.splice(index,1));
               this.setData({
                   collection
                 })
                //  console.log();
                  // 对接取消题目收藏接口
               let question_id = this.data.examdata[this.data.title].questionid
               let userid = wx.getStorageSync('userID')
               wx.request({
                   url: app.globalData.baseUrl+`/record/cancel/${userid}/${question_id}`,
                   method: 'GET',
                   success: (res) => {
                   console.log("取消收藏");
                   }
               })
           }

          },
        onChange(event){
            // 打印radio 属性拿到 name
            console.log(event);
            // 拿数据操作
            let radioarr = this.data.radioarr;
            let title = this.data.title;
            let examdata = this.data.examdata
            // event.detail 拿到 radio 属性名
            radioarr[title] = event.detail;
            // 打印选项值
            
            this.setData({
                radio: event.detail,
                radioarr: radioarr, 
            })

            if(this.data.title < this.data.examdata.length && event.detail.trim() === this.data.examdata[this.data.title].answer.trim()){
                if(!this.data.click){
                    //  console.log(this.data.question_list[this.data.question_num].id);
                     this.data.correct_question.push(this.data.examdata[this.data.title].questionid)
                }
                wx.showToast({
                    title: '答案正确',
                    icon: 'succes',
                    duration: 300,
                    mask: true
                  })
                  setTimeout(() => {
                      let grade = this.data.grade
                      grade++
                    this.setData({
                      grade,
                      click: false
                    })
                    this.nextquestion()
                  }, 300);
            }
            else {
                if (!this.data.click) {
                //   console.log(this.data.question_list[this.data.question_num].id);
                  this.data.error_question.push(this.data.examdata[this.data.title].questionid)
                }
                wx.showToast({
                  title: '答案错误',
                  icon: 'error',
                  duration: 400,
                  mask: true
                })
              }
              this.setData({
                click: true
              })
            
        },

        // 初始化数据
        async initdata(){
            // 
            let shijuantype = this.data.shijuantype
            // 
            if (shijuantype == "suiji") {
                await this.getsuijidata();
              } 
              else {
                await this.getexamdata();
              }
        },

        // 随机数据
        getsuijidata() {
            request({
              url: app.globalData.baseUrl+"/question/rand"
            }).then((res) => {
                console.log(res);
              this.setData({
                examdata: res.data,
                examlength: res.data.length
              })
              // 获取每一天题的答案
              let index = 0;
              let answer = this.data.answer
              for (const item of this.data.examdata) {
                answer[index++] = item.answer;
              }
              this.setData({
                answer
              })
            })
          },


           /**
   * api---获取考试道题
   */
  getexamdata() {
    let shijuantype = this.data.shijuantype;
    request({
      url: app.globalData.baseUrl+`/paper/shijuan/${shijuantype}`
    }).then((res) => {
    //   console.log(res);
      this.setData({
        examdata: res.data,
        examlength: res.data.length
      })
      // 获取每一天题的答案
      let index = 0;
      let answer = this.data.answer
      for (const item of this.data.examdata) {
        answer[index++] = item.answer;
      }
      this.setData({
        answer
      })
    })
  },


        // 滑动切换题目
        touchEnd(e){
            // 结束
            let endX = e.changedTouches[0].clientX;
            let endY = e.changedTouches[0].clientY;
            // 开始
            let startX = this.data.startX;
            let startY = this.data.startY;
            // 题目
            let title = this.data.title;
            // 长度
            let examlength = this.data.examlength
            // 判断区间
            if(title >= 0 && title <=examlength){
                if (endX - startX > 50 && Math.abs(endY - startY) < 50 && title > 0) { //右滑
                    title--;
                    this.setData({
                      title: title
                    })
                  }
                  else if (endX - startX < -50 && Math.abs(endY - startY) < 50 && title < examlength - 1) { //左滑
                    title++;
                    this.setData({
                      title: title++
                    })
                  }
            }
        },


        // 滑动开始
        touchStart(e) {
            // console.log(e);
            this.setData({
              startX: e.changedTouches[0].clientX,
              startY: e.changedTouches[0].clientY
            });
          },


        //   倒计时

        async ontime(e) {
            //   console.log(e);
            this.setData({
              timeData: e.detail,
            });
            let grade = this.data.grade
            if (!(e.detail.days || e.detail.hours || e.detail.minutes || e.detail.milliseconds)) {
              await this.matching();
              wx.showToast({
                title: "考试时间到了",
                icon: 'success',
                duration: 1000
              })
        
              setTimeout(() => {
                wx.navigateBack({
                  delta: 1
                })
              }, 1000)
            }
        
          },


        //   提交试卷
        sub(e){
            let that = this
            let grade = this.data.grade
            let shijuantype=this.data.shijuantype;
            // console.log(shijuantype);

            wx.showModal({
                title: '提示',
                content: '是否提交试卷',
                async success(res) {
                  if (res.confirm) {
                    that.matching();
                    if(shijuantype!="suiji"){
                      await that.subexam();
                    }
                    else{
                      await that.subsuiji();
                    }
                 
                    //  返回上一页面
                    wx.navigateTo({
                      url: `/shouchang/score/index?grade=${grade}`,
                    })
                  } else if (res.cancel) {
                    // console.log("取消了");
                  }
                }
              })
        },

        // 匹配答案
        matching(){
            let answer = this.data.answer; //获取所有的答案
            let IDs = this.data.examdata; //获取所有题目的IDs
            let radioarr = this.data.radioarr; //获取用户答的答案
            let examlength = this.data.examlength; //获取题目长度
            let grade = this.data.grade; //获取分数
            let errorindex = this.data.errorindex; //获取错题的索引
            let errorID = this.data.errorID; //获取错题的索引ID
            let correctindex = this.data.correctindex; //获取正确的索引
            let correctID = this.data.correctID; //获取正确的题的索引ID
            // console.log(IDs);
            // console.log(grade);
            // console.log(answer);
            // console.log(radioarr);
            // console.log(answer,IDs,radioarr,examlength,grade,errorindex,errorID,correctindex,correctID);
            for( let index=0 ; index <=examlength; index++)
            {
               
                if( answer[index] == radioarr[index])
                {   
                    // console.log(answer[i] == radioarr[i]);
                    // console.log(answer);
                    // console.log("dui");
                    // console.log(radioarr);
                    // grade = grade + 1
                    // console.log(answer[0] == radioarr[0]);
                    // console.log(radioarr[index]);
                    // correctID.push(IDs[index].questionid);
                    correctindex[index] = index;
                }
                else {
                    // console.log("cuo");
                    // console.log(errorIDs[index].questionid);
                    // errorID.push(IDs[index].questionid);
                    errorindex[index] = index;
                  }

                
            }
            this.setData({
                grade,
                errorindex,
                errorID,
                errorindex
              })

            // console.log("答案",answer,"题目id",IDs,"用户答案",radioarr,"长度",examlength,"分数",grade,"错误id",errorindex,"错误",errorID,"正确id",correctindex,"正确",correctID);
            console.log(grade);
        },


        // 查询试卷id
        async checkshijuan(){

            await request({

                url: app.globalData.baseUrl+"/paper/getAllPaper"
            }).then((res)=>{

                // console.log(res);
                let shijuantype=this.data.shijuantype;

                for (const item of res.data) {
                    if(item.paperTable == shijuantype){
                        this.setData({
                            paperId:item.paperId,
                            paperName:item.paperName
                        })
                    }
                }

                this.setData({
                    shijuandata: res.data
                  })
            })
        },


        // 发送试卷发数
        async subexam(){

            let userID = wx.getStorageSync('userID');

            let grade = this.data.grade;
            let paperId=this.data.paperId;
            let paperName=this.data.paperName;
            let radioarr=this.data.radioarr;
            let answerarr=[];

            for (const item in radioarr) {
                let value=radioarr[item]||"null";
                answerarr[item]=value;
              }

              let data = {
                userid: userID,
                score: grade,
                paperid:paperId,
                recordname:paperName,
                answer:answerarr
              }

              await wx.request({
                url: app.globalData.baseUrl+'/shijuan/save',
                method: 'POST',
                data: data,
                success(res) {
                //   console.log("exam=>>>",res)
                },
              })
        },


        // 发随机数据
        async subsuiji(){
            let userID = wx.getStorageSync('userID');
            let grade = this.data.grade;
            let data={
              userid:userID,
              score:grade
            }
            // console.log("suihji-----",data);
            // console.log("grade",this.data.grade);
            await wx.request({
              url: app.globalData.baseUrl+'/shijuan/lianxi',
              method: 'POST',
              data: data,
              success(res) {
                // console.log("suiji=>>>",res)
              },
            })
          },



        //   收藏
        //   collection(){
            // if(this.data.collection.indexOf(this.data.question_list[this.data.question_num].questionid)== -1){
            //     this.data.collection.push(this.data.question_list[this.data.question_num].questionid)

            //     this.data.question_list[this.data.question_num].collected = true;
            //     let question_list = this.data.question_list;
            //     this.setData({
            //         question_list
            //     })
            // }
            // let flag = this.data.flag
            // if(flag) return this.setData({ flag:false})
            // else return this.setData({flag:true})

        //   }

        //   向后端加收藏

       //  答题卡显示
    chose(){
        this.showPopup()
    },
    // 显示
    showPopup(){
        this.setData({
            show:true
        })
    },
     // 控制弹出层隐藏函数
    onClose() {
        this.setData({
        show: false
        });
    },


     // 点击题目列表的题目索引跳转题目
     changeNum(e) {
        console.log(e.currentTarget.dataset.index);
        let index = e.currentTarget.dataset.index
        this.setData({
        title: index
        })
        this.onClose()
    },


    nextquestion() {
        if (this.data.title >= 0 && this.data.title < this.data.examdata.length - 1) {
        let n = ++this.data.title
        this.setData({
            title: n
        })
        if (this.data.radio[this.data.title]) {
            // console.log(111);
            this.setData({
            click: true
            })
        } else {
            this.setData({
            click: false
            })
        }
        }
    },
})